package com.xwj.back.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xwj.back.mapper.StoreMapper;
import com.xwj.back.pojo.Store;
import com.xwj.back.service.StoreService;
import com.xwj.back.utils.listener.DataListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;

@Service
public class StoreServiceImpl implements StoreService {

    @Autowired
    private StoreMapper storeMapper;

    @Override
    public void batchExport(List<Integer> data, HttpServletResponse response) throws IOException {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        try {
            String fileName = URLEncoder.encode("门店信息表", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            QueryWrapper<Store> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("id",data);
            List<Store> stores = storeMapper.selectList(queryWrapper);
            EasyExcel.write(response.getOutputStream(),Store.class).autoCloseStream(Boolean.FALSE).sheet("门店信息").doWrite(stores);
        } catch (Exception e) {
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, String> map = new HashMap<>();
            map.put("status", "fail");
            response.getWriter().println(JSON.toJSONString(map));
        }
    }

    @Override
    public void ExportExcel(HttpServletResponse response) throws IOException {
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("门店信息表", "UTF-8");//防止乱码
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            List<Store> list = storeMapper.selectList(null);
            EasyExcel.write(response.getOutputStream(), Store.class).autoCloseStream(Boolean.FALSE).sheet("全部数据")
                    .doWrite(list);//字节输出流对象
        } catch (Exception e) {
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, String> map = new HashMap<>();
            map.put("status", "fail");
            response.getWriter().println(JSON.toJSONString(map));
        }
    }

    @Override
    public Map<String, String> ImportExcel(MultipartFile file) throws IOException {
        EasyExcel.read(file.getInputStream(),Store.class,new DataListener(storeMapper)).sheet().doRead();
        Map<String, String> map = new HashMap<>();
        map.put("message","success");
        return map;
    }

    @Override
    public JSONObject getStores(String username, String role, Integer page) {
        IPage<Store> storeIPage = new Page<>(page,6);
        JSONObject resp = new JSONObject();
        if("ROLE_BOSS".equals(role)) {
            QueryWrapper<Store> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("boss_name",username);
            Long total = storeMapper.selectCount(queryWrapper);
            List<Store> stores = storeMapper.selectPage(storeIPage, queryWrapper).getRecords();
            resp.put("stores",stores);
            resp.put("total",total);
            return resp;
        }else if("ROLE_USER".equals(role)){
            QueryWrapper<Store> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("manager",username);
            Long total = storeMapper.selectCount(queryWrapper);
            List<Store> stores = storeMapper.selectPage(storeIPage, queryWrapper).getRecords();
            resp.put("stores",stores);
            resp.put("total",total);
            return resp;
        }
        List<Store> stores = storeMapper.selectPage(storeIPage, null).getRecords();
        Long total = storeMapper.selectCount(null);
        resp.put("stores",stores);
        resp.put("total",total);
        return resp;
    }

    @Override
    public List<Store> getStoreAll() {
        return storeMapper.selectList(null);
    }

    @Override
    public String addStore(Map<String,String> data) {
        String name = data.get("name");
        String bossName = data.get("bossName");
        String phone = data.get("phone");
        String manager = data.get("manager");
        String type = data.get("type");
        String address = data.get("address");
        String business = data.get("business");
        Integer area = Integer.parseInt(data.get("area"));
        String logo = data.get("logo");
        Store store = new Store(null,name,bossName,address,phone,business,area,manager,type,logo);
        storeMapper.insert(store);
        return "success";
    }

    @Override
    public String updateStore(Map<String, String> data) {
        String role = data.get("role");
        if("ROLE_USER".equals(role))
            return "error";
        Integer id = Integer.parseInt(data.get("id"));
        String name = data.get("name");
        String bossName = data.get("bossName");
        String phone = data.get("phone");
        String manager = data.get("manager");
        String type = data.get("type");
        String address = data.get("address");
        String business = data.get("business");
        Integer area = Integer.parseInt(data.get("area"));
        String logo = data.get("logo");
        Store store = new Store(id,name,bossName,address,phone,business,area,manager,type,logo);
        storeMapper.updateById(store);
        return "success";
    }

    @Override
    public String deleteStore(Map<String, String> data) {
        String role = data.get("role");
        if("ROLE_USER".equals(role))
            return "error";
        String id = data.get("id");
        storeMapper.deleteById(id);
        return "success";
    }

    @Override
    public String deleteSelect(Map<String, String> data) {
        String role = data.get("role");
        if("ROLE_USER".equals(role))
            return "error";
        ArrayList select = JSONObject.parseObject(data.get("select"), ArrayList.class);
        storeMapper.deleteBatchIds(select);
        return "success";
    }

    @Override
    public List<Store> getStoreByType(List<String> types, String username,String role) {
        QueryWrapper<Store> queryWrapper = new QueryWrapper<>();
        if(types.size() >= 1) {
            queryWrapper.in("type", types);
            queryWrapper.orderByDesc("type");
        }
        if("ROLE_BOSS".equals(role)) {
            queryWrapper.eq("boss_name",username);
            return storeMapper.selectList(queryWrapper);
        }else if("ROLE_USER".equals(role)){
            queryWrapper.eq("manager",username);
            return storeMapper.selectList(queryWrapper);
        }
        return storeMapper.selectList(queryWrapper);
    }

    @Override
    public List<Store> getStoreByLike(String username, String role, String storeName, String storeBoss) {
        QueryWrapper<Store> queryWrapper = new QueryWrapper<>();
        if("ROLE_BOSS".equals(role)){
            queryWrapper.eq("boss_name",username);
            if(!"".equals(storeName))
                queryWrapper.like("name",storeName);
            return storeMapper.selectList(queryWrapper);
        }else if("ROLE_USER".equals(role)){
            return null;
        }
        if(!"".equals(storeName))
            queryWrapper.like("name",storeName);
        if(!"".equals(storeBoss))
            queryWrapper.like("boss_name",storeBoss);
        return storeMapper.selectList(queryWrapper);
    }
}
